package com.help10000.rms.mvp.presenter

import com.amir.common.api.CustomObserver
import com.amir.common.api.upload.FileUploadObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.FeedBackEntity
import com.amir.common.beans.FileEntity
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.LogUtils
import com.amir.common.utils.SPUtils
import com.amir.common.utils.Utils
import com.help10000.kottlinbaselib.api.upload.UploadFileRequestBody
import com.help10000.rms.mvp.view.FeedbackView
import com.help10000.rms.ui.utils.ImageCompressor
import io.reactivex.android.schedulers.AndroidSchedulers
import okhttp3.MultipartBody
import okhttp3.ResponseBody
import java.io.File
import java.net.URLEncoder

class FeedbackListPresenter(view: FeedbackView) : BasePresenter<FeedbackView>(view) {

    /**
     * 获取地址列表
     */
    fun getFeedList(page: Int) {
        val AccessToken = SPUtils.getString(Constant.AccessToken)
        val feedback = Model.getServer().feedList(AccessToken, page)
        Model.getObservable(feedback, object : CustomObserver<FeedBackEntity>(mvpView) {

            override fun success(t: FeedBackEntity) {
                mvpView?.onDataSuccess(t)
            }
        })
    }


    /**
     * 删除地址
     */
    fun deleteFeed(fid: String, pos: Int) {
        val AccessToken = SPUtils.getString(Constant.AccessToken)
        val CmpyCode = SPUtils.getString(Constant.CmpyCode)
        val api = Model.getServer().deleteFeed(AccessToken, CmpyCode, fid)
        Model.getObservable(api, object : CustomObserver<BaseResult>(mvpView) {

            override fun success(t: BaseResult) {
                mvpView?.deleteSuccess(pos)
            }
        })
    }

    /**
     * 添加反馈
     */
    fun addFeed(comments: String, imgs: String) {
        val AccessToken = SPUtils.getString(Constant.AccessToken)
        val api = Model.getServer().addFeed(AccessToken, comments, imgs)
        Model.getObservable(api, object : CustomObserver<BaseResult>(mvpView) {
            override fun success(t: BaseResult) {
                mvpView?.onSuccess()
            }
        })
    }


    var index = 0
    var fileList = mutableListOf<String>()
    fun upFile(list: MutableList<String>) {
        if (index >= list.size) {
            mvpView?.dismissLoading()
            mvpView?.fileUploadSuccess(fileList)
            return
        }

        val fileUrl = list[index]
        if (!fileUrl.startsWith("file")) {
            index++
            upFile(list)
            return
        }

        val originFile = File(fileUrl.removePrefix("file://"))
        val accessToken = SPUtils.getString(Constant.AccessToken)

        ImageCompressor.compressAsync(context = Utils.getContext(), sourceFile = originFile)
            .onErrorReturn { originFile } // 压缩失败就用原图
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ compressedFile ->
                val requestBody = UploadFileRequestBody(compressedFile, mFileUploadObserver)
                val part = MultipartBody.Part.createFormData("file",
                    URLEncoder.encode(compressedFile.name,"utf-8"),
                    requestBody)

                val upAvatar = Model.getServer().UploadFile(accessToken, part)
                Model.getObservable(upAvatar, object : CustomObserver<FileEntity>(mvpView) {
                    override fun success(t: FileEntity) {
                        fileList.add(t.FileName)
                        index++
                        upFile(list) // 递归上传下一张
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        mvpView?.dismissLoading()
                    }
                })
            }, { error ->
                LogUtils.I("FeedbackListPresenter","图片压缩失败: ${error.message}")
                index++
                upFile(list) // 压缩失败也继续下一个
            })
    }

    private val mFileUploadObserver = object : FileUploadObserver<ResponseBody>(mvpView) {
        override fun onUpLoadSuccess(t: ResponseBody) {

        }

        override fun onUpLoadFail(e: Throwable) {

        }

        override fun onProgress(progress: Int) {

        }
    }
}